require('es6-promise').polyfill();

import axios from 'axios'

function loadBills(data) {
  return {
    type: 'LOAD_BILL_DATA',
    data
  }
}

function errorAction(error) {
  return {
    type: 'ERROR_BILL',
    error
  }
}

export function apiMsgAction(msg) {
  return {
    type: 'API_MSG',
    msg
  }
}

export function createBillAsync(data) {
  return function(dispatch) {
    return axios.post('/api/bill/create', data).then(
      resp => dispatch(loadBillAsync({})),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

export function pushBillAsync(data) {
  return function(dispatch) {
    return axios.post('/api/bill/pushMessage', data).then(
      resp => dispatch(loadBillAsync({
        offset: data.offset,
        limit: data.limit,
        unit_desc: data.unit_desc
      })),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}

export function pushAllBillAsync(data) {
  var target = document.getElementById('react-root');
  showProgress(target);

  return function(dispatch) {
    return axios.post('/api/bill/pushMessageAll', data).then(function(resp) {
      dispatch(loadBillAsync(resp.data))
      dispatch(apiMsgAction("推送完成"))
      stopProgress()
    })
    .catch(function(error) {
      alert(error.data.errMsg)
      stopProgress()
    })
  };
}

export function loadBillAsync(data) {
  return function(dispatch) {
    return axios.post('/api/bill', data).then(
      resp => dispatch(loadBills(resp.data)),
      error => dispatch(apiMsgAction(error.data.errMsg))
    );
  };
}



export function uploadBillAsync(data) {
  // return function(dispatch) {
  //   return axios.post('/api/bill/upload', data).then(
  //     resp => dispatch(loadBillAsync({})),
  //     error => dispatch(apiMsgAction(error.data.errMsg))
  //   );
  // };
  var target = document.getElementById('react-root');
  showProgress(target);
  return function(dispatch) {
    return axios.post('/api/bill/upload', data)
          .then(function(resp) {

            dispatch(loadBillAsync({}))
            var amount = parseFloat(resp.data.data.amount);
            if (!isNaN(amount)) {
              amount = amount.toFixed(2)
            }
            dispatch(apiMsgAction('上传完成! 成功: '+resp.data.data.success+", 失败: "
                                +resp.data.data.failure+", 总导入金额: "+amount))
            stopProgress()
          })
          .catch(function(error) {
            console.log(error)
            dispatch(apiMsgAction(error.data.errMsg))
            stopProgress()
          })
  };
}
